package com.myservlet01;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dsna.util.images.ValidateCode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class Servlet02
 */
public class Servlet02 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet02() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		1.所有servlet 的 application, 所有servlet 共享
//		2. 获取全局配置文件
//		3. 获取当前应用任何路径下任何资源
		    ServletContext application=this.getServletContext();
		    String name=  (String) application.getAttribute("name");
		    if(name!=null) {
		        System.out.println("attribute:"+name);
		    }
		    
		    String encoding= application.getInitParameter("encoding");
		    if(encoding!=null) {
		        System.out.println("context-param:"+ encoding);
				
		    }
	//wtpwebapps\03_servlet2_5\	    
		 String path=application.getRealPath("/WEB-INF/classes/b.properties");
		 Properties pro=new Properties();
		 pro.load(new FileInputStream(path));
		 
		 
		 System.out.println("key:"+ pro.getProperty("key"));  // /表示当前项目根目录
		 
		 // 服务器 默认reponse 返回iso-8859-1，不支持中文,告诉服务器使用utf-8编码
		 response.setCharacterEncoding("utf-8");
		 //告诉浏览器使用编码
	//	 response.setHeader("content-type", "utf-8");
		 
		
		 
	//	 PrintWriter out=response.getWriter();
	//	 out.print("<html><head><meta charset='UTF-8'></head><body>你好</body></html>");
		
		// 或者如下:
		// response.setHeader("content-type", "text/html;charset=utf-8"); 
		// out.print("您好,tim");
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	
		 
		 //显示下载
		// downloadImage(application,request,response);
	
		 
	  //设置1s钟刷新一次 ,	请求  http://localhost:8081/03_servlet2_5/Servlet02
	  //	 response.setIntHeader("refresh", 1); 
		 //实现验证码功能
	  //	 test1(response);
		 
		 
		 
		 //用库实现验证码
			//告诉客户端不使用缓存
//			response.setHeader("pragma", "no-cache");
//			response.setHeader("cache-control", "no-cache");
//			response.setIntHeader("expires", 0);
//			
//			
//			ValidateCode vc = new ValidateCode(110, 25, 4, 9);
//			String code = vc.getCode();//得到生成的字符
//			vc.write(response.getOutputStream());	 
		 
		 
		 
	// 设置3s钟跳转
//		 response.setHeader("content-type", "text/html;charset=utf-8"); 
//		 response.getWriter().write("注册成功!3秒钟跳到主页");
//		 response.setHeader("refresh", "3;url=/03_servlet2_5/Servlet03");
		 
		 
	// 重定向
//		 response.setStatus(302);
//		 response.setHeader("location", "/03_servlet2_5/Servlet03");
		 
		 //写法2 
	//response.sendRedirect("/03_servlet2_5/Servlet03");	 

	
	// 15、HttpServletRequest对象介绍
	 // GET  	请求方式
	System.out.println(request.getMethod()); 
	//03_servlet2_5/Servlet02
	//请求行中资源部分
	System.out.println(request.getRequestURI()); 
	//完整请求地址
//http://localhost:8081/03_servlet2_5/Servlet02  
	System.out.println(request.getRequestURL());
///03_servlet2_5	当前应用虚拟目录
    System.out.println(request.getContextPath());
 //username=tom     返回请求参数部分
    System.out.println(request.getQueryString());
	
    String header= request.getHeader("User-Agent");
    if(header.toLowerCase().contains("msie")){
    	System.out.println("IE");
    }else if(header.toLowerCase().contains("firefox")) {
     	System.out.println("火狐");
    }else if(header.toLowerCase().contains("chrome")) {
     	System.out.println("google");
    }
    
    
//    accept  image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*
//    accept-language  zh-CN
//    cache-control  no-cache
//    ua-cpu  AMD64
//    accept-encoding  gzip, deflate
//    user-agent  Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/7.0)
//    host  localhost:8081
//    connection  Keep-Alive
   //获取所有头
    Enumeration  names= request.getHeaderNames();
    while(names.hasMoreElements()) {
    	String e= (String) names.nextElement();
    	System.out.println(e+"  "+request.getHeader(e));
    }
    
    //18、与获取表单数据相关的方法
    //只能解决post访求的乱码
    request.setCharacterEncoding("utf-8");
    String userName= request.getParameter("userName");
    userName=new String(userName.getBytes("iso-8859-1"),"utf-8");
    String pwd= request.getParameter("pwd");   
    pwd=new String( pwd.getBytes("iso-8859-1"),"utf-8");
    String sex= request.getParameter("sex");  
    sex=new String( sex.getBytes("iso-8859-1"),"utf-8");
    String[] hobby=request.getParameterValues("hobby");
    for(int i=0;i<hobby.length;i++) {
    	  System.out.println(new String( hobby[i].getBytes("iso-8859-1"),"utf-8"));
    }
    String city= request.getParameter("city");
    city=new String( city.getBytes("iso-8859-1"),"utf-8");
    System.out.println(userName+"  "+ pwd + "  "+sex +"  "+ city);
  
    
    //
    
    
    
} 
	
	
	
	private void test1(HttpServletResponse response) throws IOException {
		int width = 110;
		int height = 25;
		//在内存中创建一个图像对象
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		//创建一个画笔
		Graphics g = img.getGraphics();
		
		//给图片添加背景色
		g.setColor(Color.PINK);//设置一个颜色
		//设置填充坐标
		g.fillRect(1, 1, width-2, height-2);//填充颜色
		
		//给边框一个色
		g.setColor(Color.RED);
		g.drawRect(0, 0, width-1, height-1);//设置边框的显示坐标
		
		//设置文本样式
		g.setColor(Color.BLUE);
		g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 15));
		
		//给图片添加文本
		Random rand = new Random();
		int position = 20;
		for (int i = 0; i < 4; i++) {
			int rand1= rand.nextInt(10);
			System.out.print(rand1+"");
			g.drawString(rand1+"", position, 20);//给图片填充文本
			position+=20;
		}
		System.out.println("\n");
		
		//添加9条干扰线
		for (int i = 0; i < 9; i++) {
			g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
		}
		//将图片对象以流的方式输出的客户端
		ImageIO.write(img, "jpg", response.getOutputStream());
	}

	
	
	
	public void downloadImage(ServletContext application,HttpServletRequest request, HttpServletResponse response) {
		 response.setHeader("content-type", "utf-8");
		 String path_dn=application.getRealPath("/WEB-INF/res/2024-04-06-img.jpg");
	     System.out.println("path_dn:" + new File(path_dn).exists());
	     try {
			FileInputStream  fis = new FileInputStream(path_dn);
			   //创建字节输出流response的
		     ServletOutputStream sos= response.getOutputStream();
		     String filename = path_dn.substring(path_dn.lastIndexOf("\\")+1);
		     // filename ios-8859-1 转化为 utf-8
		     filename = URLEncoder.encode(filename,"utf-8");
		     System.out.println("filename:"+  filename);
		     
		     //告诉客户端要下载的文件
		     response.setHeader("content-disposition", "attachment;filename="+filename);
		     response.setHeader("content-type", "image/jpeg");
		    
		     
		     int len= -1;
		     byte[] b=new byte[1024];
		     while((len=fis.read(b))!=-1) {
		    	 sos.write(b,0,len);
		     }
		     sos.flush();
		     sos.close();
		     fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	// 图片直接显示到浏览器
	public void showImg(ServletContext application,HttpServletResponse response) {
		 //文件下载
		 String path_dn=application.getRealPath("/WEB-INF/res/2024-04-06-img.jpg");
	     System.out.println("path_dn:" + new File(path_dn).exists());
	     FileInputStream fis;
		try {
			fis = new FileInputStream(path_dn);
			
			   //创建字节输出流response的
		     ServletOutputStream sos= response.getOutputStream();
		     int len= -1;
		     byte[] b=new byte[1024];
		     while((len=fis.read(b))!=-1) {
		    	 sos.write(b,0,len);
		     }
		     sos.flush();
		     sos.close();
		     fis.close();
		     
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
